package com.woniuxy.factory.controller;

import com.woniuxy.factory.entity.Product;
import com.woniuxy.factory.entity.ResponseResult;
import com.woniuxy.factory.exception.BusinessException;
import com.woniuxy.factory.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class ProductController {

    @Autowired
    ProductService productService;
    //获取商品信息并分页
    @ResponseBody
    @GetMapping("/product")
    public ResponseResult<List<Product>> getProductAll(int page, int limit){
        Product product = new Product();
        ResponseResult<List<Product>>  responseReslt = productService.getProductAll(page,limit,product);
        return responseReslt;
    }
    //获取指定条件的所有商品
    @ResponseBody
    @PostMapping("/products")
    public ResponseResult<List<Product>> getProductAll(Product product){
        ResponseResult<List<Product>>  responseReslt = productService.getProducts(product);
        return responseReslt;
    }
    //新增指定商品
    @PostMapping("/addproduct")
    @ResponseBody
    public ResponseResult addproduct(Product product){
        if (product==null){
            return new ResponseResult(1,"新增商品信息有误",null,null);
        }
        try {
            return productService.addproduct(product);
        }catch (BusinessException e){
            return new ResponseResult(0,e.getMessage(),null,null);
        }
    }

    //修改商品信息
    @ResponseBody
    @PostMapping("/updateproduct")
    public ResponseResult updateproduct(Product product){
        if (product==null){
            return new ResponseResult(1,"修改的商品信息有误",null,null);
        }
        try {
            return  productService.updateproduct(product);

        }catch (BusinessException e){
            return new ResponseResult(1,e.getMessage(),null,null);
        }
    }
    //删除指定产品信息
    @ResponseBody
    @PostMapping("/deleteproduct")
    public ResponseResult deleteProduct(String prdId){
        if (prdId==null || prdId==""){
            return new ResponseResult(1,"删除的商品信息有误",null,null);
        }
        return productService.deleteProduct(prdId);
    }
    @PostMapping("/deleteproducts")
    @ResponseBody
    public ResponseResult deleteProducts(@RequestParam("prdIds[]")String[] prdIds){
        if (prdIds.length==0){
            return new ResponseResult(1,"所删商品信息有误",null,null);
        }
        return productService.deleteProducts(prdIds);
    }
}
